//
//  QKOAuthViewController.swift
//  微博
//
//  Created by qiukai on 16/4/9.
//  Copyright © 2016年 仇恺. All rights reserved.
//

import UIKit

class QKOAuthViewController: UIViewController {
    private lazy var webView = UIWebView()
    // MARK: - 监听方法
    /// 点击了关闭按钮
    @objc private func didClickCloseButton(){
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
        
    }
    /// 点击了自动填充按钮
    @objc private func didClickFillButton(){
        let js = "document.getElementById('userId').value = '18610772514';" +
        "document.getElementById('passwd').value = 'ca518340';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    
    // MARK: - 界面设置
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.whiteColor()
        webView.delegate = self
        title = "登陆新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "didClickCloseButton")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "didClickFillButton")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.webView.loadRequest(NSURLRequest(URL: QKNetworkTools.sharedTools.oauthURL))
    }
}
// MARK: - UIWebViewDelegate
extension QKOAuthViewController: UIWebViewDelegate{
    /// 将要加载请求的代理方法
    ///
    /// - parameter webView:        webView自己
    /// - parameter request:        将要加载的请求
    /// - parameter navigationType: navigationType 页面跳转的方式
    ///
    /// - returns: true加载false不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        /// 判断要跳转的是否是百度，如果是继续执行，不是则直接加载
        guard let url = request.URL where url.host == "www.baidu.com" else{
            return true
        }
        /// 将query中code＝前缀去掉如果不为空继续执行，如果为空直接不允许加载
        guard let query = url.query where query.hasPrefix("code=") else{
            print("取消授权")
            return false
        }
        /// 经过前面两部可以确定，此时是访问百度授权，且query已取到值
        /// 切掉query前五位
        let code = query.substringFromIndex("code=".endIndex)

        print("授权码是\(code)")
        
        QKNetworkTools.sharedTools.loadAccessToken(code) { (result, error) in
            if error != nil {
                print("出错了")
                return
            }
            print(result)
        }
       
        didClickCloseButton()
        return false
    }
    
    
    
}